Page({
  /**
   * 页面的初始数据
   */
  data: {
    recommendedSongs: [],
    nowPlaying: {
      title: "暂无播放",
      artist: "未知歌手",
      coverUrl: "",
    },
    isPlaying: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("推荐歌曲页面onLoad");

    // 加载推荐歌曲
    this.fetchRecommendedSongs();

    // 检查当前播放的歌曲
    this.checkNowPlaying();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("推荐歌曲页面onShow");

    // 检查当前播放的歌曲
    this.checkNowPlaying();

    // 检查是否需要刷新数据
    if (this.data.recommendedSongs.length === 0) {
      this.fetchRecommendedSongs();
    }
  },

  /**
   * 获取推荐歌曲
   */
  fetchRecommendedSongs: function () {
    const token = wx.getStorageSync("access_token");
    const that = this;

    wx.showLoading({
      title: "加载中...",
    });

    wx.request({
      url: "https://smartsound.top/personalized/newsong",
      method: "GET",
      data: {
        limit: 50, // 获取更多推荐歌曲
      },
      header: {
        Authorization: token ? `Bearer ${token}` : "",
        "content-type": "application/json",
      },
      success(res) {
        wx.hideLoading();
        console.log("推荐歌曲:", res.data);
        if (res.data && res.data.result) {
          const songs = res.data.result.map((item) => {
            return {
              id: item.id,
              name: item.name,
              artist: item.song.artists[0].name,
              album: item.song.album.name,
              picUrl: item.picUrl,
            };
          });
          that.setData({
            recommendedSongs: songs,
          });
        }
      },
      fail(err) {
        wx.hideLoading();
        console.error("获取推荐歌曲失败:", err);
        wx.showToast({
          title: "获取推荐歌曲失败",
          icon: "none",
        });
      },
    });
  },

  /**
   * 检查当前播放的歌曲
   */
  checkNowPlaying: function () {
    const app = getApp();
    if (app.globalData && app.globalData.nowPlaying) {
      this.setData({
        nowPlaying: app.globalData.nowPlaying,
        isPlaying: app.globalData.isPlaying || false,
      });
    }

    // 注册播放状态变化回调
    app.playStatusCallback = (isPlaying) => {
      this.setData({ isPlaying });
    };

    // 注册歌曲变化回调
    app.songChangeCallback = (song) => {
      this.setData({
        nowPlaying: song,
        isPlaying: true,
      });
    };
  },

  /**
   * 处理歌曲点击
   */
  handleSongTap: function (e) {
    const songId = e.currentTarget.dataset.id;
    const songName = e.currentTarget.dataset.name;
    const songIndex = this.data.recommendedSongs.findIndex(
      (song) => song.id == songId
    );

    if (songIndex === -1) {
      console.error("无法找到歌曲信息");
      return;
    }

    const songInfo = this.data.recommendedSongs[songIndex];
    console.log("点击歌曲:", songId, songName);

    // 获取全局app
    const app = getApp();

    // 设置播放列表
    app.globalData.currentSongList = [...this.data.recommendedSongs];

    // 播放选中的歌曲
    app.playSong(songInfo);

    // 更新本地播放状态
    this.setData({
      nowPlaying: {
        id: songInfo.id,
        title: songInfo.name,
        artist: songInfo.artist,
        coverUrl: songInfo.picUrl,
      },
      isPlaying: true,
    });

    // 跳转到歌曲详情页
    wx.navigateTo({
      url: `/pages/song/song?id=${songId}&name=${encodeURIComponent(songName)}`,
    });
  },

  /**
   * 处理正在播放栏点击
   */
  handleNowPlayingTap: function () {
    // 跳转到歌曲详情页
    if (this.data.nowPlaying.id) {
      wx.navigateTo({
        url: `/pages/song/song?id=${
          this.data.nowPlaying.id
        }&name=${encodeURIComponent(this.data.nowPlaying.title)}`,
      });
    }
  },

  /**
   * 切换播放状态
   */
  togglePlayState: function (e) {
    // 阻止事件冒泡
    e.stopPropagation();

    const app = getApp();
    if (this.data.isPlaying) {
      app.pauseAudio();
    } else {
      app.playAudio();
    }

    this.setData({
      isPlaying: !this.data.isPlaying,
    });
  },
});
